package org.wzl.todolisthelper.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.wzl.todolisthelper.convert.TaskCommentConvert;
import org.wzl.todolisthelper.domain.TaskComment;
import org.wzl.todolisthelper.domain.TaskEvent;
import org.wzl.todolisthelper.dto.AddTaskComment;
import org.wzl.todolisthelper.enumerate.AddTaskEventDTO;
import org.wzl.todolisthelper.enumerate.TaskEventEnum;
import org.wzl.todolisthelper.service.ProfileService;
import org.wzl.todolisthelper.service.TaskCommentService;
import org.wzl.todolisthelper.mapper.TaskCommentMapper;
import org.springframework.stereotype.Service;
import org.wzl.todolisthelper.service.TaskEventService;
import org.wzl.todolisthelper.utils.UserUtil;
import org.wzl.todolisthelper.vo.TaskCommentVO;

import java.util.List;

/**
* @author weizhilong
* @description 针对表【t_comment_task】的数据库操作Service实现
* @createDate 2025-04-05 20:55:30
*/
@Service
public class TaskCommentServiceImpl extends ServiceImpl<TaskCommentMapper, TaskComment>
    implements TaskCommentService {

    @Resource
    private TaskEventService taskEventService;

    @Resource
    private ProfileService profileService;

    @Resource
    private TaskCommentConvert taskCommentConvert;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTaskComment(AddTaskComment addTaskComment) {
        //1、先建立一个任务事件，事件类型为评论
        AddTaskEventDTO addTaskEventDTO = new AddTaskEventDTO();
        addTaskEventDTO.setEventType(TaskEventEnum.COMMENT);
        addTaskEventDTO.setEventName(TaskEventEnum.COMMENT.getDesc());
        addTaskEventDTO.setEventDesc("用户[" + profileService.getUserInfo().getNickname() + "]添加了评论");
        addTaskEventDTO.setTaskId(addTaskComment.getTaskId());
        TaskEvent taskEvent = taskEventService.addTaskEvent(addTaskEventDTO);

        //2、建立评论
        TaskComment taskComment = new TaskComment();
        taskComment.setCommentValue(addTaskComment.getComment());
        taskComment.setTaskId(addTaskComment.getTaskId());
        taskComment.setEventId(taskEvent.getId());
        taskComment.setCreateUserId(UserUtil.getCurrentUserId());
        save(taskComment);
    }

    @Override
    public List<TaskCommentVO> getTaskComments(String taskId) {
        List<TaskComment> list = list(Wrappers.<TaskComment>lambdaQuery()
                .eq(TaskComment::getTaskId, taskId)
                .orderBy(true, true, TaskComment::getCreateDate));
        return list.stream().map(taskComment -> {
            TaskCommentVO vo = taskCommentConvert.toVO(taskComment);
            vo.setCreateUser(profileService.getById(taskComment.getCreateUserId()));
            return vo;
        }).toList();
    }

}




